package com.hbhmzy.contact;


import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.hbhmzy.call.R;

public class ContactAddActivity extends Activity {

	private Button cancel;
	private Button finish;
	private EditText etName;
	private EditText etNumber;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.contact_add);

		initView();
		initListener();
		//设置状态栏颜色
//		Sofia.with(this).statusBarBackground(getResources().getColor(R.color.GREEN_ROOT));
	}
	
	//重写返回键
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction()==KeyEvent.ACTION_DOWN){
            finish();
		}
        return true;
    }

	private void initView() {
		cancel = findViewById(R.id.root_cancel);
		TextView title = findViewById(R.id.root_title3);
		title.setText("新建联系人");
		finish = findViewById(R.id.root_ok);
		etName = findViewById(R.id.addContact_name);
		etNumber = findViewById(R.id.addContact_number);
	}

	private void initListener() {
		//取消，返回联系人列表界面
		cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
                finish();
			}
		});

		// 新建联系人完成点击事件
		finish.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 去掉姓名和号码中的空格
				String name = etName.getText().toString().replace(" ", "");
				String number = etNumber.getText().toString().replace(" ", "");
				if (("".equals(name)) && ("".equals(number))) {
                    Toast.makeText(ContactAddActivity.this, "您未填写有效信息", Toast.LENGTH_SHORT).show();
				}else {//如果姓名为空，电话不为空，则姓名=电话
					if( "".equals(name) && !"".equals(number) ){
						name=number;
					}
					String sortkey = ContactsActivity.getSortKey(name);	//如果name为空会导致出错---->>>
					//将新建的联系人信息插入数据库
					ContactDBHelper dbHelper = new ContactDBHelper(ContactAddActivity.this, "mycontact.db3", null, 1);
					ContactDBManager.insert(dbHelper.getReadableDatabase(), name, number, sortkey, null, null);
					//获取新建的联系人信息, 通知更新联系人列表, 更新联系人列表界面
					Toast.makeText(ContactAddActivity.this, "添加成功！", Toast.LENGTH_SHORT).show();
					setResult(Activity.RESULT_OK);
					finish();
				}
			}
		});
	}
}
